//
//  JPushModule.m
//  XYLib
//
//  Created by XYLib on 9/8/18.
//  Copyright © 2018年 XYLib. All rights reserved.
//

#import "JPushModule.h"
#import <JPush/JPUSHService.h>
@interface JPushModule()
{
    NSInteger getTagsSeq;
    NSInteger setTagsSeq;
}
@end

@implementation JPushModule

WX_EXPORT_METHOD(@selector(getAllTags:))
WX_EXPORT_METHOD(@selector(addTags::))
WX_EXPORT_METHOD(@selector(setTags::))
WX_EXPORT_METHOD(@selector(deleteTags::))
WX_EXPORT_METHOD_SYNC(@selector(getJpushRegistrationID))

-(void)getAllTags:(WXModuleKeepAliveCallback)callback{
    getTagsSeq++;
    [JPUSHService getAllTags:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {
        if (callback && seq == self->getTagsSeq){
            if (0 == iResCode) {
                callback(@{@"code":@(iResCode),@"tags":iTags?[iTags allObjects]:@""}, NO);
            }else{
                callback(@{@"code":@(iResCode)}, NO);
            }
        }
    } seq: getTagsSeq];
}

-(void)addTags:(NSArray*)tags :(WXModuleKeepAliveCallback)callback{
    if (tags && tags.count>0) {
        setTagsSeq++;
        NSSet* set = [NSSet setWithArray:tags];
        [JPUSHService addTags:set completion:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {
            if (callback && seq == self->setTagsSeq) {
                callback(@{@"code":@(iResCode),@"tags":iTags?[iTags allObjects]:@""}, NO);
            }
        } seq:setTagsSeq];
    }
}

-(NSString *)getJpushRegistrationID{
    NSString *str = [JPUSHService registrationID];
    return str;
}

-(void)setTags:(NSArray*)tags :(WXModuleKeepAliveCallback)callback{
    setTagsSeq++;
    if (tags && tags.count>0) {
        NSSet* set = [NSSet setWithArray:tags];
        [JPUSHService setTags:set completion:^(NSInteger iResCode, NSSet *iTags, NSInteger seq){
            if (callback && seq == self->setTagsSeq) {
                callback(@{@"code":@(iResCode),@"tags":iTags?[iTags allObjects]:@""}, NO);
            }
        } seq:setTagsSeq];
    }else{
        [JPUSHService cleanTags:^(NSInteger iResCode, NSSet *iTags, NSInteger seq){
            if (callback && seq == self->setTagsSeq) {
                callback(@{@"code":@(iResCode),@"tags":iTags?[iTags allObjects]:@""}, NO);
            }
        } seq:setTagsSeq];
    }
}

-(void)deleteTags:(NSArray*)tags :(WXModuleKeepAliveCallback)callback{
    if (tags && tags.count>0) {
        NSSet* set = [NSSet setWithArray:tags];
        [JPUSHService deleteTags:set completion:^(NSInteger iResCode, NSSet *iTags, NSInteger seq){
            callback(@{@"code":@(iResCode)}, NO);
        } seq:0];
    } else {
        callback(@{@"code":@(0)}, NO);
    }
}
@end
